package com.xmall.config;

import cn.hutool.core.util.IdUtil;
import com.xmall.define.constants.CommonConstants;
import com.xmall.msg.queue.CommonModule;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

@Configuration
public class AmqpCommonExchangeConfig {

    @Resource
    private RabbitAdmin rabbitAdmin;

    /**
     * 字典更新流向
     * 广播交换机（dict.fanout.exchange） --> 匿名队列
     */
    @Bean
    public Exchange dictFanoutExchange() {
        return new FanoutExchange(CommonModule.CommonExchange.DICT_FANOUT_EXCHANGE);
    }
    @Bean
    public Queue dictQueue() {
        return new AnonymousQueue(() -> CommonConstants.Queue.DICT_ANONYMOUS_QUEUE_PREFIX + IdUtil.getSnowflakeNextId());
    }
    @Bean
    public Binding dictBinding() {
        return BindingBuilder.bind(dictQueue()).to(dictFanoutExchange()).with("").noargs();
    }

    /**
     * 操作日志流向
     * 操作日志：路由键（operate.log.key） --> 直接交换机（operate.log.direct.exchange）
     *                                        --> 队列（operate.log.queue）
     */
    @Bean
    public Exchange operateLogDirectExchange() {
        return new DirectExchange(CommonModule.OperateLog.OPERATE_LOG_DIRECT_EXCHANGE);
    }
    @Bean
    public Queue operateLogQueue() {
        Queue queue = new Queue(CommonModule.OperateLog.OPERATE_LOG_QUEUE, true, false, false);
        rabbitAdmin.declareQueue(queue);
        return queue;
    }
    @Bean
    public Binding operateLogBinding() {
        return BindingBuilder.bind(operateLogQueue()).to(operateLogDirectExchange()).with(CommonModule.OperateLog.OPERATE_LOG_ROUTING_KEY).noargs();
    }
}
